package com.hx.vending.service.impl;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.hx.vending.bean.*;
import com.hx.vending.bean.config.AlipayConfig;
import com.hx.vending.controller.AliPayController;
import com.hx.vending.dao.*;
import com.hx.vending.service.IRefundService;
import com.hx.vending.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2019/1/25.
 */
@Service
public class RefundServiceImpl implements IRefundService {

    @Resource
    private RefundMapper refundMapper;
    @Resource
    private OnlineOrderMapper onlineOrderMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private CapitalFlowMapper capitalFlowMapper;
    @Resource
    private OrderBuyMapper orderBuyMapper;

    private static final Logger logger = LoggerFactory.getLogger(RefundServiceImpl.class);

    @Override
    public int insertSelective(Refund refund) {
        return refundMapper.insertSelective(refund);
    }

    @Override
    public Msg aliPayRefund(Integer onlineOrderId,Integer orderBuyId,Double refund_amount) {
        OnlineOrder o = new OnlineOrder();
        o.setOnlineOrderId(onlineOrderId);
        OnlineOrder onlineOrder = onlineOrderMapper.selectByPrimaryKeySelective(o);
        User u = new User();
        u.setUserId(onlineOrder.getOnlineOrderUserId());
        User user = userMapper.selectByPrimaryKey(u);
        if(user.getUserMoney() < refund_amount){
            return Msg.fail().add("msg","该商户余额不足");
        }
        if(user.getUserAlipayBalance() < refund_amount){
            return Msg.fail().add("msg","支付宝余额不足");
        }
        //订单号
        //String trade_no = onlineOrder.getOnlineOrderDealNumber();
        //部分退款
        String out_request_no = DateUtil.getAllTime()+ ToolUtil.generateNonceStr(4);
        // 实例化客户端
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID,
                AlipayConfig.APP_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.input_charset,
                AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.sign_type);
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeRefundModel refundModel = new AlipayTradeRefundModel();
        refundModel.setTradeNo(onlineOrder.getOnlineOrderDealNumber());
        refundModel.setOutTradeNo(onlineOrder.getOnlineOrderMerchantNumber());
        refundModel.setRefundAmount(refund_amount.toString());
        refundModel.setRefundReason("商品退款");
        refundModel.setOutRequestNo(out_request_no);
        //refundModel.setStoreId("NJ_S_001");
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        request.setBizModel(refundModel);
        //request.setNotifyUrl(null);
        try{
            AlipayTradeRefundResponse response = alipayClient.execute(request);
            System.out.println("=============交易结果"+response.getMsg()+"\n");
            System.out.println(response.getBody());
            System.out.println("================结果"+response.isSuccess());
            if(response.isSuccess()){
                //退款金额
                System.out.println("===============退款金额"+response.getRefundFee());
                System.out.println("===============买家id"+response.getBuyerUserId());
                System.out.println("===============支付宝交易号"+response.getTradeNo());
                System.out.println("===============退款时间"+response.getGmtRefundPay());
                //退款金额
                Double money = Double.parseDouble(response.getRefundFee());
                Refund refund = new Refund();
                refund.setRefundMoney(money);
                //商家id
                refund.setRefundUserId(onlineOrder.getOnlineOrderUserId());
                //退款支付时间
                refund.setRefundTime(DateUtil.getTime(response.getGmtRefundPay()));
                //支付宝交易号
                refund.setRefundOrderId(onlineOrderId);
                refund.setRefundState(1);
                int i = refundMapper.insertSelective(refund);
                if(i > 0){
                   /* User u = new User();
                    u.setUserId(onlineOrder.getOnlineOrderUserId());
                    User user = userMapper.selectByPrimaryKey(u);*/
                    //修改商户余额
                    user.setUserMoney(BigDecimalUtils.sub(user.getUserMoney(),money));
                    user.setUserAlipayBalance(BigDecimalUtils.sub(user.getUserAlipayBalance(),money));
                    userMapper.updateByPrimaryKeySelective(user);
                    //添加流水
                    CapitalFlow capitalFlow = new CapitalFlow();
                    capitalFlow.setCapitalFlowUserId(onlineOrder.getOnlineOrderUserId());
                    capitalFlow.setCapitalFlowTransactionNumber(response.getTradeNo());
                    capitalFlow.setCapitalFlowTransactionAmount(money);
                    capitalFlow.setCapitalFlowPaymentType(2);
                    capitalFlow.setCapitalFlowTransactionType(5);
                    capitalFlow.setCapitalFlowTime(DateUtil.getTime(response.getGmtRefundPay()));
                    capitalFlow.setCapitalFlowState(2);
                    capitalFlow.setCapitalFlowUserMoney(BigDecimalUtils.sub(user.getUserMoney(),money));
                    capitalFlow.setCapitalFlowRemarks("商品退款到支付宝");
                    capitalFlowMapper.insertSelective(capitalFlow);
                    if(ToolUtil.isNotEmpty(orderBuyId)){
                        //修改退款状态
                        OrderBuy orderBuy = new OrderBuy();
                        orderBuy.setOrderBuyId(orderBuyId);
                        orderBuy.setOrderBuyRefund(1);
                        orderBuyMapper.updateByPrimaryKeySelective(orderBuy);
                    }else{
                        OrderBuy ob = new OrderBuy();
                        ob.setOrderBuyParentId(onlineOrderId);
                        List<OrderBuy> orderBuyList = orderBuyMapper.selectByExampleSelective(ob);
                        for(int j = 0;j < orderBuyList.size();j++){
                            if(orderBuyList.get(j).getOrderBuyRefund() == 0 || orderBuyList.get(j).getOrderBuyRefund() == 2){
                                orderBuyList.get(j).setOrderBuyRefund(1);
                                orderBuyMapper.updateByPrimaryKeySelective(orderBuyList.get(j));
                            }
                        }
                    }

                    //修改订单退款状态
                    /*onlineOrder.setOnlineOrderRefund(2);
                    this.onlineOrderMapper.updateByPrimaryKeySelective(onlineOrder);*/
                }
                return Msg.success().add("msg","退款成功");
            }else {
                if(ToolUtil.isNotEmpty(orderBuyId)){
                    //修改退款状态
                    OrderBuy orderBuy = new OrderBuy();
                    orderBuy.setOrderBuyId(orderBuyId);
                    orderBuy.setOrderBuyRefund(2);
                    orderBuyMapper.updateByPrimaryKeySelective(orderBuy);

                }else{
                    OrderBuy ob = new OrderBuy();
                    ob.setOrderBuyParentId(onlineOrderId);
                    List<OrderBuy> orderBuyList = orderBuyMapper.selectByExampleSelective(ob);
                    for(int j = 0;j < orderBuyList.size();j++){
                        if(orderBuyList.get(j).getOrderBuyRefund() == 0 || orderBuyList.get(j).getOrderBuyRefund() == 2){
                            orderBuyList.get(j).setOrderBuyRefund(2);
                            orderBuyMapper.updateByPrimaryKeySelective(orderBuyList.get(j));
                        }
                    }
                }
                /*onlineOrder.setOnlineOrderRefund(3);
                this.onlineOrderMapper.updateByPrimaryKeySelective(onlineOrder);*/
                //修改订单退款状态
                Refund refund = new Refund();
                refund.setRefundTime(DateUtil.getTime());
                refund.setRefundState(2);
                refund.setRefundMoney(refund_amount);
                refund.setRefundOrderId(onlineOrderId);
                refundMapper.insertSelective(refund);
                if(response.getSubCode().equals("ACQ.SELLER_BALANCE_NOT_ENOUGH")){

                    String pushMessage = "账户异常:\n异常类型:支付宝账户退款余额不足";
                    PushUtils.getInstance().pushMessage("18654568090",String.format(pushMessage));
                    PushUtils.getInstance().pushMessage("15562649697",String.format(pushMessage));
                    return Msg.fail().add("msg","服务器正在忙于结算，请5-10分钟后再试!");
                }
                return Msg.fail().add("msg",response.getSubMsg());
            }
        }catch(Exception e){
            e.printStackTrace();
            logger.error("支付宝退款错误！",e.getMessage());
        }
        return Msg.fail();
    }

}
